/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package org.dyndns.freed0m.web.secureauth.DAL;

import org.dyndns.freed0m.web.secureauth.bean.Password;
import org.dyndns.freed0m.web.secureauth.bean.User;
import org.dyndns.freed0m.web.secureauth.Utils.HibernateUtil;
import org.hibernate.Query;
import org.hibernate.Session;

/**
 *
 * @author lvallet
 */
public final class UserDAO {
    public static User signIn(String username, String password){
        User user = new User();
        user.setUsername(username);
        Password pwd = new Password();
        pwd.setHashPassword(password);
        Session hibSes = HibernateUtil.getCurrentSession();
        hibSes.save(user);
        pwd.setIdUser(user.getId());
        //pwd.setPassword(password);
        hibSes.save(pwd);
        HibernateUtil.closeSession();
        return user;
    }

    public static User logIn(String username, String password) throws Exception {
        Session hibSes = HibernateUtil.getCurrentSession();
        Query requeteUser = hibSes.createQuery("from User where username= :username");
        requeteUser.setString("username", username);
        User user = (User) requeteUser.uniqueResult();
        if(user == null){
            throw new Exception("Unknown User!");
        }
        Query requetePassword = hibSes.createQuery("from Password where password= :password");
        requetePassword.setString("password", password);
        HibernateUtil.closeSession();
        return user;
    }
      private UserDAO(){
      }
      
}
